package com.xdwanj.filter;

import com.mysql.jdbc.StringUtils;
import com.xdwanj.servlet.PageServlet;
import com.xdwanj.util.UrlUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CommodityFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("进入了CommodityFilter...");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = null;

        String coid = request.getParameter(PageServlet.COID);
        String pagePosition = request.getParameter(PageServlet.POSITION);

        if (!StringUtils.isNullOrEmpty(pagePosition)) { // 页面坐标不为空，有指定页面定位
            switch (pagePosition) {
                case PageServlet.COMMODITY:  // 去往商品页面

                    if (!StringUtils.isStrictlyNumeric(coid)) { // coid为空，或者为垃圾值，重定向回商城页面
                        url = request.getContextPath() + UrlUtil.getUrl(PageServlet.REQUEST_MAPPING, new String[]{PageServlet.POSITION, PageServlet.SHOP});
                        System.out.println("url = " + url);
                        response.sendRedirect(url);
                    }
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
            }

            // 其他不被限制的页面直接放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 页面坐标为空，送他去主页
        url = request.getContextPath() + UrlUtil.getUrl(PageServlet.REQUEST_MAPPING, new String[]{PageServlet.POSITION, PageServlet.SHOP});
        System.out.println("url = " + url);
        response.sendRedirect(url);
    }

    @Override
    public void destroy() {

    }
}
